package com.atguigu.tran;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author yhm
 * @create 2024-04-02 10:30
 */
public class Test05_FlatMapReplace {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 2. 读取数据源
        DataStreamSource<String> lineDs = env.socketTextStream("hadoop102", 7777);

        // 3. 处理数据
        lineDs.flatMap(new FlatMapFunction<String, WaterSensor>() {
            @Override
            public void flatMap(String value, Collector<WaterSensor> out) throws Exception {
                try {
                    String[] words = value.split(",");
                    if (words.length == 3){
                        out.collect(new WaterSensor(words[0],Long.valueOf(words[1]),Integer.valueOf(words[2])));
                    }else{
                        // 也是脏数据
                        System.out.println("脏数据为:" + value + ",无法转换为javaBean");
                    }
                }catch (Exception e){
                    // 处理脏数据
                    System.out.println("脏数据为:" + value + ",无法转换为javaBean");
//                    e.printStackTrace();
                }

            }
        }).print();

        // 4. 输出

        // 5. 执行环境
        env.execute();
    }
}
